//
//  HMMyMessageController.m
//  仿真开发
//
//  Created by Cloud on 2017/3/22.
//  Copyright © 2017年 B.HOPE. All rights reserved.
//

#import "HMMyMessageController.h"
#import <Masonry.h>
#import "HMDefaultsTool.h"
#import "HMLoginModel.h"
#import "HMMyMessageCell.h"
#import "provinceModel.h"
#import "HMTool.h"



@interface HMMyMessageController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>



//头像按钮
@property (nonatomic, strong)UIButton *icon;

//模型数组
@property (nonatomic, strong)NSMutableArray *arrList;

//当前用户的模型
@property (nonatomic, strong)HMLoginModel *model;

//数据
@property (nonatomic, strong)NSString *label;

//相应的行和组
@property(nonatomic,assign)NSInteger  section;
@property(nonatomic,assign)NSInteger  row;

//输入的文本
@property (nonatomic, strong)NSString *text;

//UItableView
@property(nonatomic,weak)UITableView  *tabView;

@property(weak, nonatomic)UIView *Uview;

//数据源
@property (strong,nonatomic)NSArray *array;
//城市数据源
@property (strong,nonatomic)NSArray *cities;
//当前的省城
@property(nonatomic, assign) NSInteger currentSelectedProvice;

//要得到的相应的省和城市
@property(nonatomic,copy)NSString *name;

@property(nonatomic,copy)NSString *city;

@end

@implementation HMMyMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self loadData];
    
}

//创建控制器时加载数据
- (void)initWithDic:(NSDictionary *)dic
{
    HMLoginModel *model = [HMLoginModel loginWithDict:dic];
    _model = model;
    
}



/**
 创建个人信息UI界面
 */
- (void)setupUI
{
    //创建一个全屏的tableView
    UITableView *tab = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    tab.dataSource = self;
    tab.delegate = self;
    
    //创建TableView的headView
    UIImageView *headView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1429862008539"]];
    headView.userInteractionEnabled = YES;
    
    [self.view addSubview:tab];
    //添加头部视图
    tab.tableHeaderView = headView;
    
    [tab registerClass:[HMMyMessageCell class] forCellReuseIdentifier:@"HM"];
    
    //创建头像button
    UIButton *iconBtn = [[UIButton alloc] init];
    iconBtn.layer.backgroundColor = [UIColor whiteColor].CGColor;
    iconBtn.layer.borderWidth = 1;
    iconBtn.layer.cornerRadius = 35;
    iconBtn.clipsToBounds = YES;
    
    self.icon = iconBtn;
    
    //设置初始化头像
    UIImage *image;
    NSString *name = [HMDefaultsTool objetForKey:@"currentID"];
    NSData *iconData = [HMDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-ICON",name]];
    UIImage *iconImage = [UIImage imageWithData:iconData];
    
    if (iconImage) {
        image = iconImage;
    }else{
        image = [UIImage imageNamed:@"doctor_defaultphoto_male"];
    }
    [iconBtn setBackgroundImage:image forState:UIControlStateNormal];

    //小头像的点击事件
    [iconBtn addTarget:self action:@selector(touchIconBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [headView addSubview:iconBtn];
    
    //设置头像button约束
    CGFloat margin =70;
    [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(headView);
        make.centerY.equalTo(headView.mas_bottom).mas_offset(-10);
        make.size.mas_equalTo(CGSizeMake(margin, margin));
    }];
    

    [_arrList addObject:_model];
    
}


#pragma mark - 个人信息数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrList.count;
}

- (HMMyMessageCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"mess.ab"];
    
    NSDictionary *model = _arrList[indexPath.row];
    
    HMMyMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HM" forIndexPath:indexPath];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.foModel = model;
    
    void(^labelBlock)() = ^(NSString *label)
    {
        self.label = label;
    };
    
    cell.labelBlock = labelBlock;
    
    
    return cell;
}

#pragma mark - 头像点击事件
- (void)touchIconBtn:(UIButton *)sender{
    
    //创建图片选择器
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    imagePicker.allowsEditing = YES;
    
    imagePicker.delegate = self;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - 保存用户选择的图片为头像图片

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo
{
    [self.icon setImage:image forState:UIControlStateNormal];
    NSData *data = UIImagePNGRepresentation(image);
    
    [HMDefaultsTool saveObject:data forKey:[NSString stringWithFormat:@"%@-ICON",[HMDefaultsTool objetForKey:@"currentID"]]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"01" object:nil userInfo:nil];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 加载数据
- (void)loadData
{
    
    NSString *name = [HMDefaultsTool objetForKey:@"currentID"];
    NSData *modelData = [HMDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-MODEL",name]];
    HMLoginModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];
    _model = model;

    _arrList = [NSMutableArray arrayWithObjects:@{@"姓名" : model.name},@{@"年龄":model.age},@{@"性别":model.sex},@{@"身高":model.height},@{@"体重":model.weight},@{@"籍贯":model.address},@{@"常居地":model.residence},@{@"联系方式":model.phoneNumber},@{@"证件号码":model.IdNumber}, nil];
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"mess.ab"];
    
    [NSKeyedArchiver archiveRootObject:model toFile:path];
    
    [self.tabView reloadData];
}

#pragma mark - 点击cell的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.section = indexPath.section;
    self.row = indexPath.row;
    switch (indexPath.row) {
        case 0:
            //修改姓名
            [self upCellDateWith:@"name"];
            
            break;
        case 1:
            //修改年龄
            [self upCellDateWith:@"age"];
            break;
        case 2:
            //修改性别
            [self upCellDateWith:@"sex"];
            break;
        case 3:
            //修改身高
            [self upCellDateWith:@"height"];
            break;
        case 4:
            //修改体重
            [self upCellDateWith:@"weight"];
            break;
        case 5:
            //修改籍贯
            [self updata];
            break;
        case 6:
            //修改常居地
            [self updata];
            break;
        case 7:
            //修改联系方式
            [self upCellDateWith:@"phoneNumber"];
            break;
        case 8:
            //修改证件号码
            [self upCellDateWith:@"IdNumber"];
            break;
            
        default:
            break;
    }
    [self.tabView reloadData];
}

#pragma mark - 点击修改内容
- (void)upCellDateWith:(NSString *)title
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入修改信息";
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *login = alert.textFields.firstObject;
        NSString *a = login.text;
        _text = a;
        NSDictionary *model = _arrList[self.row];
        NSDictionary *newModel = @{[model allKeys].lastObject:a};
        NSString *key = [newModel allKeys].lastObject;
        id value = [NSString stringWithFormat:@"%@",newModel[key]];
        [self upPlishWithTitle:value];
        [_arrList replaceObjectAtIndex:self.row withObject:newModel];
        [self.tabView reloadData];
        
    }];
    
    [self.tabView reloadData];
    [alert addAction:cancel];
    
    [alert addAction:ok];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    [self upPlishWithTitle:title];
    NSIndexPath *idx = [NSIndexPath indexPathForRow:self.row inSection:0];
    [self.tabView reloadRowsAtIndexPaths:@[idx] withRowAnimation:UITableViewRowAnimationAutomatic];
    
}


#pragma mark - 点击弹出滚动视图


/**
 修改居住信息方法
 */
- (void)updata
{
    [self loadPVdata];
    
    UIView *vw = [[UIView alloc] init];
    
    vw.backgroundColor = [UIColor lightGrayColor];
    
    _Uview = vw;
    
    [self.view addSubview:vw];
    
    [vw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(240);
    }];
    
    UIPickerView *pv = [[UIPickerView alloc] init];
    
    pv.backgroundColor = [UIColor whiteColor];
    
    _pickView = pv;
    
    pv.delegate = self;
    
    pv.dataSource = self;
    
    pv.showsSelectionIndicator = YES;
    
    [vw addSubview:pv];
    
    [pv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(vw);
        make.height.mas_offset(193);
    }];
    
    UIButton *btn = [[UIButton alloc]init];
    [btn setTintColor:[UIColor whiteColor]];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitle:@"确定" forState:UIControlStateNormal ];
    btn.titleLabel.font = [UIFont systemFontOfSize:20.0];
    
    [vw addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(vw).offset(-15);
        make.top.equalTo(vw).offset(6);
    }];
    
    [btn addTarget:self action:@selector(touchOK) forControlEvents:UIControlEventTouchUpInside];
}



/**
 点击pickerView确定按钮
 */
- (void)touchOK
{
    [_Uview removeFromSuperview];
    NSLog(@"%@",_name);
    NSLog(@"%@",_city);
    
}


/**
 创建pickerView的数据
 */
- (void)loadPVdata
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"province.plist" ofType:nil];
    
    NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    self.cities = arr;
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSDictionary *dict in arr) {
        provinceModel *model = [provinceModel provinceWithDict:dict];
        [arrM addObject:model];
    }
    _array = arrM;
}

#pragma mark - pickerView数据源方法

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return _array.count;
    }else{
        provinceModel *model = self.array[self.currentSelectedProvice];
        return model.cities.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        provinceModel *model = self.array[row];
        
        self.name = model.name;
        return model.name;
    }else{
        provinceModel *model = self.array[self.currentSelectedProvice];
        self.city = model.cities[row];
        return model.cities[row];
    }
}


/**
 当改变省份时，重新加载第2列的数据，部分加载
 */
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        self.currentSelectedProvice = row;
        [pickerView reloadComponent:1];
    }
}



#pragma mark - 修改数据
- (void)upPlishWithTitle:(NSString *)title
{
    switch (self.row) {
        case 0:
            _model.name = title;
            break;
        case 1:
            _model.age = title;
            break;
        case 2:
            _model.sex = title;
            break;
        case 3:
            _model.height = title;
            break;
        case 4:
            _model.weight = title;
            break;
        case 5:
            _model.address = title;
            break;
        case 6:
            _model.residence = title;
            break;
        case 7:
            _model.phoneNumber = title;
            break;
        case 8:
            _model.IdNumber = title;
            break;
            
        default:
            break;
    }
    [HMTool updateCurrentIDModel:_model];
    [self.tabView reloadData];
}
@end
